package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppUserThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnLikesBehaviorServiceImpl extends ServiceImpl<ApUnLikesBehaviorMapper,ApUnlikesBehavior> implements ApUnLikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    /**
     * 保存不喜欢行为方法
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //判断用户登录状态
        ApUser user = AppUserThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry;
        if (user != null) {
            //根据用户id查询用户行为实体
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
        } else {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        }
        if(apBehaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户行为实体数据不存在");
        }
        //根据行为实体id和文章id判断是否存在不喜欢行为数据
        ApUnlikesBehavior apUnlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));

        if(apUnlikesBehavior!=null){
            //修改参数
            apUnlikesBehavior.setType(dto.getType());
        }else {
            //不存在则创建不喜欢行为对象
            apUnlikesBehavior=new ApUnlikesBehavior();
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setType(dto.getType());
            apUnlikesBehavior.setCreatedTime(new Date());
        }
        saveOrUpdate(apUnlikesBehavior);
        return ResponseResult.okResult();
    }
}
